package com.epfresh.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.adapter.AddressAdapter;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.basedialog.CustomDialog;
import com.epfresh.bean.Address;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.DataManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wzh on 16-7-18.
 */
public class ReceiverAddressActivity extends BaseActivity {

    ListView lv;
    View vAddAddress;
    View vEmpty, ll_bottom;

    AddressAdapter adapter;

    List<Address> list = new ArrayList<>();

    String addressId;

    boolean isLimitArea;
    boolean isForResult;
    private TextView txt_add_address;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_receiver_address);

        if (savedInstanceState != null) {
            getIntent().putExtra("isLimitArea", savedInstanceState.getBoolean("isLimitArea", false));
            getIntent().putExtra("isForResult", savedInstanceState.getBoolean("isForResult", false));
        }
        toolbarTitle.setText("收货地址");
        ivBack.setVisibility(View.VISIBLE);

        rightbtn.setText("添加");
        rightbtn.setVisibility(View.GONE);


        isLimitArea = getIntent().getBooleanExtra("isLimitArea", false);
        isForResult = getIntent().getBooleanExtra("isForResult", false);

        initView();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isLimitArea", isLimitArea);
        outState.putBoolean("isForResult", isForResult);
        super.onSaveInstanceState(outState);
    }

    private void initView() {
        ll_bottom = findViewById(R.id.ll_bottom);
        txt_add_address = findViewById(R.id.txt_add_address);
        txt_add_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intoAddAddress(null);
            }
        });

        vEmpty = findViewById(R.id.ll_add_address);
        vAddAddress = findViewById(R.id.nodate_start);
        vAddAddress.setOnClickListener(this);
        vEmpty.setVisibility(View.GONE);
        ll_bottom.setVisibility(View.VISIBLE);
        lv = (ListView) findViewById(R.id.lv);


        addressId = getIntent().getStringExtra("address_id");
        adapter = new AddressAdapter(this, list);

        adapter.setAddressId(addressId);

        adapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Address address = list.get(i);
                if (address != null) {
                    if (l == 1) {//删除
                        delete(address, i);
                    } else if (l == 2) {//编辑


                        intoAddAddress(address);
                    }
                }
            }
        });

        lv.setAdapter(adapter);
        if (isForResult) {
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    Address address = list.get(i);
//                Log.d("address", "addr:" + new Gson().toJson(address));
                    Intent intent = new Intent();
                    intent.putExtra("address", new Gson().toJson(address));
                    setResult(RESULT_OK, intent);
                    finish();
                }
            });
        }

        requestDelivery();
    }

    public void intoAddAddress(Address address) {
        Intent intent = new Intent(this, AddAddressActivity.class);
        if (address != null) {
            intent.putExtra("address", new Gson().toJson(address));
        }
        intent.putExtra("isLimitArea", isLimitArea);
        startActivityForResult(intent, 0x1992);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == 0x1992) {
            list.clear();
            adapter.notifyDataSetChanged();
            requestDelivery();
        }
    }

    public void delete(final Address address, final int position) {
        CustomDialog.Builder builder = new CustomDialog.Builder(mContext);

        builder.setTitleVisible(false).setMessage("确定删除地址吗？")//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件

                        delete(address.getId(), position);
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();

            }

        });//在按键响应事件中显示此对话框
        builder.create().show();
    }

    @Override
    public void onRightClick() {

        intoAddAddress(null);
    }

    @Override
    protected void onToolbarBack() {

        int i = adapter.calCurrentIndex();
        if (i == -1 && list.size() == 0) {
            Intent intent = new Intent();
            intent.putExtra("is_empty", true);
            setResult(RESULT_OK, intent);
            finish();
        } else if (i > -1) {

            Address address = list.get(i);
            Intent intent = new Intent();
            intent.putExtra("address", new Gson().toJson(address));
            setResult(RESULT_OK, intent);
            finish();
        }

        finish();
    }

    @Override
    public void onBackPressed() {
        onToolbarBack();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.nodate_start:
                onRightClick();
                break;
        }
    }

    OnRequestListener<List<Address>> onRequestAddressListener = new OnRequestListener<List<Address>>() {
        @Override
        public List<Address> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<List<Address>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            showExceptionView(R.mipmap.order_no, o + "", 1);
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            showExceptionView(R.mipmap.order_no, o + "", 1);
        }

        @Override
        public void onStart(Object o) {

            showProgressView();
        }

        @Override
        public void onResponse(ResponseEntity<List<Address>> responseEntity, Object o) {

            showMainView();
            List<Address> responseElement = responseEntity.getResponseElement();

            if (responseElement != null) {
                for (Address address : responseElement) {
                    if (getIntent().getStringExtra("address_id") != null) {
                        address.setHaveSelect(true);
                    } else {
                        address.setHaveSelect(false);
                    }
                }
                if (responseElement.size() > 0 && TextUtils.isEmpty(addressId)) {
                    addressId = responseElement.get(0).getId();
                    adapter.setAddressId(addressId);
                }
                list.clear();
                list.addAll(responseElement);
                adapter.notifyDataSetChanged();
                if (list.size() == 0) {
                    lv.setVisibility(View.GONE);
                    vEmpty.setVisibility(View.VISIBLE);
                    ll_bottom.setVisibility(View.GONE);
//                    rightbtn.setVisibility(View.GONE);
                } else {
                    vEmpty.setVisibility(View.GONE);
                    ll_bottom.setVisibility(View.VISIBLE);
                    lv.setVisibility(View.VISIBLE);
//                    rightbtn.setVisibility(View.VISIBLE);
                }
            }
        }
    };

    public void requestDelivery() {

        RequestEntityMap re = new RequestEntityMap();

        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_account_address_list);

        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        if (isLimitArea)
            re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());


        request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_account_address_list, onRequestAddressListener);

    }


    OnRequestListener<Map<String, Boolean>> onRequestDeleteListener = new OnRequestListener<Map<String, Boolean>>() {
        @Override
        public Map<String, Boolean> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, Boolean>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<Map<String, Boolean>> responseEntity, Object o) {


            Map<String, Boolean> responseElement = responseEntity.getResponseElement();
            if (responseElement != null && responseElement.size() > 0) {//删除成功

                Boolean success = responseElement.get("success");

                if (success != null && success) {
                    RequestTag tag = (RequestTag) o;
                    list.remove(tag.action);

                    if (list.size() == 0) {
                        lv.setVisibility(View.GONE);
                        vEmpty.setVisibility(View.VISIBLE);
                        ll_bottom.setVisibility(View.GONE);
//                        rightbtn.setVisibility(View.GONE);
                    } else {
                        addressId = list.get(0).getId();
                        adapter.setAddressId(addressId);
                        vEmpty.setVisibility(View.GONE);
                        ll_bottom.setVisibility(View.VISIBLE);
                        lv.setVisibility(View.VISIBLE);
//                        rightbtn.setVisibility(View.VISIBLE);
                    }
                    adapter.notifyDataSetChanged();
                }

            }

        }
    };

    public void delete(String id, int position) {

        RequestEntityMap re = new RequestEntityMap();

        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_account_address_setDeleted);

        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        re.putParameter("id", id);
        re.putParameter("isDeleted", true);

        RequestTag tag = new RequestTag();
        tag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_account_address_setDeleted;
        tag.action = position;
        request(re, tag, onRequestDeleteListener);

    }


}
